﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PaoPaoCompnent : MonoBehaviour {



    private MeshRenderer meshRenderer;
    private MeshRenderer hintRenderer;

    private Transform m_hintTarget;

    private void Awake()
    {
        meshRenderer = transform.GetComponent<MeshRenderer>();

        m_hintTarget = transform.GetChild(0);
        if (m_hintTarget != null)
        {
            hintRenderer = m_hintTarget.GetComponent<MeshRenderer>();
        }
    }

    public void SetTexture(Texture texture)
    {
        if (hintRenderer != null)
        {
            hintRenderer.material.SetTexture("_MainTex", texture);
        }
    }

    public void UpdateActive(bool value, bool isShowAnimation)
    {
        if (isShowAnimation)
            Show(value);
        else
        {
            meshRenderer.material.SetFloat("_Transparency", value ? 1 : 0);
            hintRenderer.material.SetFloat("_Transparency", value ? 1 : 0);
        }
    }

    private void Show(bool value)
    {
        if (value)
        {
            StartCoroutine(FadeIn());
        }
        else
        {
            StartCoroutine(FadeOut());
        }

    }

    IEnumerator FadeIn()
    {
        if (m_hintTarget == null || meshRenderer == null || hintRenderer == null)
            yield break;

        meshRenderer.material.SetFloat("_Transparency", 0);
        hintRenderer.material.SetFloat("_Transparency", 0);

        float val = 0;
        while (true)
        {
            val += Time.deltaTime;
            meshRenderer.material.SetFloat("_Transparency", val);
            hintRenderer.material.SetFloat("_Transparency", val);
            if (val >= 1)
                break;
            yield return null;
        }

        //val = 0;
        //while (true)
        //{
        //    val += Time.deltaTime;
        //    hintRenderer.material.SetFloat("_Transparency", val);
        //    if (val >= 1)
        //        break;
        //    yield return null;
        //}
        meshRenderer.material.SetFloat("_Transparency", 1);
        hintRenderer.material.SetFloat("_Transparency", 1);
    }

    IEnumerator FadeOut()
    {
        if (m_hintTarget == null || meshRenderer == null || hintRenderer == null)
            yield break;

        meshRenderer.material.SetFloat("_Transparency", 0);
        hintRenderer.material.SetFloat("_Transparency", 0);
        yield break;

        float val = 1;
        while (true)
        {
            val -= Time.deltaTime;
            meshRenderer.material.SetFloat("_Transparency", val);
            hintRenderer.material.SetFloat("_Transparency", val);
            if (val <= 0)
                break;
            yield return null;
        }
        meshRenderer.material.SetFloat("_Transparency", 0);
        hintRenderer.material.SetFloat("_Transparency", 0);
    }


}
